import Zookeeper from 'node-zookeeper-client';
import ZKResponseEnum from "../entity/ZKResponseEnum.mjs";
import {host} from "../config/ZkConfig.mjs";

export default class ZkClient {
    zk;

    constructor() {
        this.zk = Zookeeper.createClient(host, {sessionTimeout: 5000});
        this.zk.connect();

        this.zk.on("connected", () => {
            console.log("====zk connected====");
        });
    }

    /**
     * 设置zk值
     * @param key zk key
     * @param value zk value
     */
    setKey(key, value) {
        const _this = this;
        return new Promise((resolve, reject) => {
            _this.zk.create(`/${key}`, Buffer.from(value), (err, path) => {
               if (err) {
                   return reject(err);
               }
               return resolve(ZKResponseEnum.SUCCESS);
            });
        });
    }

    getKey(key) {
        const _this = this;
        return new Promise((resolve, reject) => {
            _this.zk.getData(`/${key}`, (err, data, stat) => {
                if (err) {
                    return reject(err);
                }
                return resolve(data.toString());
            });
        });
    }

    delKey(key) {
        const _this = this;
        return new Promise((resolve, reject) => {
            _this.zk.remove(`/${key}`, (err) => {
                if (err) {
                    return reject(err);
                }
                console.log("del key: " + key);
                return resolve(ZKResponseEnum.SUCCESS);
            });
        });
    }

    close() {
        this.zk.close();
        console.log("====zk disconnected====");
    }
}
